import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.regex.*;

/**
 * 
 * Parses files, adding the included files (includes in " ") to a list, which can then be
 * retrieved.
 *
 */
public class CppParser implements Parser {
	private final static String START_OF_INCLUDE_DIRECTIVE = "#include \"";
	private final static String END_OF_INCLUDE_DIRECTIVE = "\"";
	
	LinkedList<String> mFileNamesIncluded = new LinkedList<String>();
	
	
	public CppParser() {
	}
	
	/**
	 * @param fileToParse - The file to parse. Must be a .cpp or .h-file
	 * @return returns true if the file the was a cpp-file and could be parsed, false otherwise.
	 */
	public boolean parse(File fileToParse) {
		if(!isCppFile(fileToParse))
			return false;
		
		BufferedReader r;
		try {
			r = new BufferedReader(new InputStreamReader(new FileInputStream(fileToParse)));
			
			String theLine = r.readLine();
			while(theLine != null) {
				String headerName = null;
				
				Pattern p = Pattern.compile("^" + START_OF_INCLUDE_DIRECTIVE);
				Matcher m = p.matcher(theLine);
				boolean mFound = m.find();
				System.out.println(mFound);
				
				Pattern q = Pattern.compile(END_OF_INCLUDE_DIRECTIVE + "$");
				Matcher n = q.matcher(theLine);
				boolean nFound = n.find();
				System.out.println(nFound);
				
				int startIndex = 0;
				int endIndex = 0;			
				if(mFound == true && nFound == true) {
					System.out.println("entering");
					startIndex = m.end();
					endIndex = n.end();
					System.out.println(startIndex);
					headerName = theLine.substring(startIndex, endIndex-1);
					assert headerName.length() > 0;
					mFileNamesIncluded.add(headerName);
				}
				theLine = r.readLine();
			}
		} catch (IOException e) {
			System.out.println(e.getCause().getMessage());
			e.printStackTrace();
		}		
		
		return true;
		
	}
	
	public LinkedList<String> getFilesIncluded() {
		assert mFileNamesIncluded != null : "mFileNamesIncluded was null.";
		return mFileNamesIncluded;
	}
	
	private boolean isCppFile(File f) {
		assert f != null : "file provided was null";
		boolean isValid = false;
		if(f.getName().endsWith(".cpp") || f.getName().endsWith(".h")) {
			isValid = true;
		}
		return isValid;
	}
	
	public static void main(String[] args) {
		//tester for CppParser
		CppParser parser = new CppParser();
		File file = new File(
				"I:\\Documents and Settings\\ivar\\Desktop\\somestuff\\experimenting\\experimenting\\Main.cpp");
		System.out.println(parser.parse(file));
		
		for(String s: parser.getFilesIncluded()) {
			System.out.println(s);
		}
	}
}
